//
//  OperationWorker.h
//  XUtils
//
//  Created by Xu Deheng on 12-4-1.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

#ifndef DATA_KILOBYTES
    #define DATA_KILOBYTES   1024
#endif

#define RUNLOOP_MODE___  1

#define HTTP_POST_METHOD    @"POST"
#define HTTP_GET_METHOD     @"GET"
#define HTTP_HEAD_METHOD    @"HEAD"
#define HTTP_PUT_METHOD     @"PUT"
#define HTTP_DELETE_METHOD  @"DELETE"
#define HTTP_TRACE_METHOD   @"TRACE"
#define HTTP_CONNECT_METHOD @"CONNECT"

@class URLConnectionOperation;

@protocol URLConnectionOperationDelegate

@optional
- (void)connectionOperation:(URLConnectionOperation*)connectionOperation didFailedWithError:(NSError*)error;
- (void)connectionOperation:(URLConnectionOperation *)connectionOperation didReveivedData:(NSData*)theData;
- (void)connectionOperation:(URLConnectionOperation*)connectionOperation didReceivedResponse:(NSURLResponse*)theResponse;
- (void)connectionOperation:(URLConnectionOperation*)connectionOperation DidFinishedLoading:(NSData*)loadedData;
- (void)connectionOperationDidFinishedLoading:(URLConnectionOperation*)connectionOperation;

@end

@interface URLConnectionOperation : NSOperation<
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_5_0
    NSURLConnectionDelegate, NSURLConnectionDataDelegate
#endif
>
{
@public
    BOOL _isConcurrent;
    BOOL _isFinished;
    BOOL _isExecuting;
    NSURL *url;
    
@private
    NSObject<URLConnectionOperationDelegate> *operationDelegate;
    BOOL canLoadData_;
    NSMutableData *dataBuffer;
    NSUInteger totalDataLength;
    
    NSInteger httpStatusCode;
    NSString *httpMethod;
    NSMutableArray *params;
    NSMutableDictionary *headFields;
}

@property (nonatomic, retain) NSURL *url;
@property (nonatomic, readonly) NSURLConnection *connection;
@property (nonatomic, assign) NSObject<URLConnectionOperationDelegate> *operationDelegate;
@property (nonatomic, retain) NSString *httpMethod;
@property (nonatomic, readonly) NSData *loadedData;
@property (nonatomic, readonly) NSMutableArray *params;
@property (nonatomic, retain) NSMutableDictionary *headFields;

+ (NSOperationQueue*)mainQueue;
+ (NSOperationQueue*)networkQueue;

- (id)initWithURL:(NSURL *)url;
- (id)initWithURL:(NSURL *)aUrl canLoadData:(BOOL)loadData;
- (void)addParamValue:(id)value forKey:(NSString*) key;
- (void)startAsynchronized;
- (void)startSynchronized;

@end

/*
 get URLConnectionOperation object at index in the array
 */
@interface NSArray (URLConnectionOperation)
- (URLConnectionOperation *)urlConnectionOperationAtIndex:(NSUInteger)aIndex;
@end


